<template>
  <div class="my-activities-page">
    <div class="container">
      <h1 class="page-title">我的活动</h1>
      
      <div class="activities-content">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="我参与的" name="participated">
            <!-- 筛选条件 -->
            <div class="filter-section">
              <el-select
                v-model="participatedFilters.status"
                placeholder="活动状态"
                class="filter-select"
                @change="handleFilterChange"
              >
                <el-option label="全部" value="" />
                <el-option label="报名中" value="PUBLISHED" />
                <el-option label="进行中" value="ONGOING" />
                <el-option label="已结束" value="FINISHED" />
                <el-option label="已取消" value="CANCELLED" />
              </el-select>
              
              <el-input
                v-model="participatedFilters.keyword"
                placeholder="搜索活动名称或内容"
                class="filter-input"
                @keyup.enter="handleFilterChange"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            
            <!-- 活动列表 -->
            <div v-if="loading" class="loading-container">
              <el-skeleton :rows="3" animated />
            </div>
            
            <div v-else-if="participatedActivities.length === 0" class="empty-container">
              <el-empty description="暂无参与的活动" />
            </div>
            
            <div v-else class="activities-list">
              <ActivityCard
                v-for="activity in participatedActivities"
                :key="activity.id"
                :activity="activity"
                @click="goToDetail(activity.id)"
              />
            </div>
            
            <!-- 分页 -->
            <div v-if="participatedActivities.length > 0" class="pagination-container">
              <el-pagination
                v-model:current-page="participatedPageNum"
                v-model:page-size="participatedPageSize"
                :page-sizes="[5, 10, 20]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="participatedTotal"
                @size-change="handleParticipatedSizeChange"
                @current-change="handleParticipatedCurrentChange"
              />
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="我创建的" name="created">
            <!-- 筛选条件 -->
            <div class="filter-section">
              <el-select
                v-model="createdFilters.status"
                placeholder="活动状态"
                class="filter-select"
                @change="handleFilterChange"
              >
                <el-option label="全部" value="" />
                <el-option label="草稿" value="DRAFT" />
                <el-option label="已发布" value="PUBLISHED" />
                <el-option label="进行中" value="ONGOING" />
                <el-option label="已结束" value="FINISHED" />
                <el-option label="已取消" value="CANCELLED" />
              </el-select>
              
              <el-input
                v-model="createdFilters.keyword"
                placeholder="搜索活动名称或内容"
                class="filter-input"
                @keyup.enter="handleFilterChange"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              
              <el-button type="primary" class="create-btn" @click="$router.push('/activity/create')">
                <el-icon><Plus /></el-icon>
                创建活动
              </el-button>
            </div>
            
            <!-- 活动列表 -->
            <div v-if="loading" class="loading-container">
              <el-skeleton :rows="3" animated />
            </div>
            
            <div v-else-if="createdActivities.length === 0" class="empty-container">
              <el-empty description="暂无创建的活动" />
              <el-button type="primary" style="margin-top: 20px;" @click="$router.push('/activity/create')">
                创建第一个活动
              </el-button>
            </div>
            
            <div v-else class="activities-list">
              <div v-for="activity in createdActivities" :key="activity.id" class="activity-item">
                <ActivityCard
                  :activity="activity"
                  @click="goToDetail(activity.id)"
                />
                <div class="activity-actions">
                  <el-button size="small" type="primary" @click.stop="editActivity(activity.id)">
                    编辑
                  </el-button>
                  <el-button size="small" @click.stop="viewParticipants(activity.id)">
                    参与者
                  </el-button>
                  <el-button
                    v-if="getMappedStatus(activity.status) === 'PUBLISHED' || getMappedStatus(activity.status) === 'DRAFT'"
                    size="small"
                    type="danger"
                    @click.stop="handleCancelActivity(activity)"
                  >
                    取消
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div v-if="createdActivities.length > 0" class="pagination-container">
              <el-pagination
                v-model:current-page="createdPageNum"
                v-model:page-size="createdPageSize"
                :page-sizes="[5, 10, 20]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="createdTotal"
                @size-change="handleCreatedSizeChange"
                @current-change="handleCreatedCurrentChange"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 参与者对话框 -->
      <el-dialog
        v-model="showParticipantsDialog"
        title="活动参与者"
        width="700px"
      >
        <div v-if="participantsLoading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        
        <div v-else-if="participants.length === 0" class="empty-participants">
          <el-empty description="暂无参与者" />
        </div>
        
        <div v-else class="participants-list">
          <el-table :data="participants" style="width: 100%">
            <el-table-column prop="userName" label="用户名" width="120" />
            <el-table-column prop="nickname" label="昵称" width="120" />
            <el-table-column prop="email" label="邮箱" width="200" />
            <el-table-column prop="phone" label="手机号" width="120" />
            <el-table-column prop="registrationTime" label="报名时间">
              <template #default="scope">
                {{ formatDate(scope.row.registrationTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">
                  {{ getRegistrationStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" v-if="currentActivityNeedApproval">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status === 'PENDING'"
                  size="small"
                  type="primary"
                  @click="handleApproveRegistration(scope.row.id)"
                >
                  同意
                </el-button>
                <el-button
                  v-if="scope.row.status === 'PENDING'"
                  size="small"
                  type="danger"
                  @click="handleRejectRegistration(scope.row.id)"
                >
                  拒绝
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div v-if="participants.length > 0" class="dialog-footer">
          <el-button type="primary" @click="exportParticipants">导出参与者</el-button>
        </div>
      </el-dialog>
      
      <!-- 取消活动对话框 -->
      <el-dialog
        v-model="showCancelDialog"
        title="取消活动"
        width="500px"
      >
        <el-form :model="cancelForm" :rules="cancelRules" ref="cancelFormRef">
          <el-form-item label="取消原因" prop="reason">
            <el-input
              v-model="cancelForm.reason"
              type="textarea"
              :rows="3"
              placeholder="请输入取消活动的原因"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showCancelDialog = false">取消</el-button>
            <el-button type="primary" :loading="cancelling" @click="submitCancel">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ActivityCard from '../components/ActivityCard.vue'
import { ElMessage } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { getUserParticipatedActivities, getUserCreatedActivities, cancelActivity } from '../api/activity'
import { getActivityRegistrations, approveRegistration, rejectRegistration } from '../api/registration'
import { mapStatusToFrontend } from '../utils/common'

export default {
  name: 'MyActivities',
  components: {
    ActivityCard,
    Search,
    Plus
  },
  setup() {
    const router = useRouter()
    
    // 数据状态
    const activeTab = ref('participated')
    const participantsLoading = ref(false)
    const cancelling = ref(false)
    const loading = ref(false)
    
    // 参与的活动数据
    const participatedPageNum = ref(1)
    const participatedPageSize = ref(10)
    const participatedFilters = ref({
      status: '',
      keyword: ''
    })
    const participatedActivities = ref([])
    const participatedTotal = ref(0)
    
    // 创建的活动数据
    const createdPageNum = ref(1)
    const createdPageSize = ref(10)
    const createdFilters = ref({
      status: '',
      keyword: ''
    })
    const createdActivities = ref([])
    const createdTotal = ref(0)
    
    // 参与者数据
    const participants = ref([])
    const showParticipantsDialog = ref(false)
    const currentActivityId = ref('')
    const currentActivityNeedApproval = ref(false)
    
    // 取消活动表单
    const showCancelDialog = ref(false)
    const activityToCancel = ref(null)
    const cancelForm = ref({
      reason: ''
    })
    const cancelFormRef = ref(null)
    
    // 获取参与的活动列表
    const fetchParticipatedActivities = async () => {
      if (activeTab.value !== 'participated') return
      
      try {
        loading.value = true
        const params = {
          pageNum: participatedPageNum.value,
          pageSize: participatedPageSize.value,
          status: participatedFilters.value.status,
          keyword: participatedFilters.value.keyword
        }
        
        const response = await getUserParticipatedActivities(params)
        participatedActivities.value = response.data || []
        participatedTotal.value = response.total || 0
      } catch (error) {
        ElMessage.error('获取参与活动列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取创建的活动列表
    const fetchCreatedActivities = async () => {
      if (activeTab.value !== 'created') return
      
      try {
        loading.value = true
        const params = {
          pageNum: createdPageNum.value,
          pageSize: createdPageSize.value,
          status: createdFilters.value.status,
          keyword: createdFilters.value.keyword
        }
        
        const response = await getUserCreatedActivities(params)
        createdActivities.value = response.data || []
        createdTotal.value = response.total || 0
      } catch (error) {
        ElMessage.error('获取创建活动列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取活动参与者
    const fetchParticipants = async () => {
      if (!currentActivityId.value) return
      
      try {
        participantsLoading.value = true
        const response = await getActivityRegistrations(currentActivityId.value)
        participants.value = response.data || []
      } catch (error) {
        ElMessage.error('获取参与者列表失败')
      } finally {
        participantsLoading.value = false
      }
    }
    

    
    // 编辑活动
    const editActivity = (activityId) => {
      router.push(`/activity/edit/${activityId}`)
    }
    
    // 查看参与者
    const viewParticipants = (activityId) => {
      currentActivityId.value = activityId
      showParticipantsDialog.value = true
      fetchParticipants()
    }
    
    // 处理取消活动
    const handleCancelActivity = (activity) => {
      activityToCancel.value = activity
      cancelForm.value.reason = ''
      showCancelDialog.value = true
    }
    
    // 提交取消活动
    const submitCancel = async () => {
      if (!cancelFormRef.value || !activityToCancel.value) return
      
      try {
        await cancelFormRef.value.validate()
        cancelling.value = true
        
        await cancelActivity({
          activityId: activityToCancel.value.id,
          reason: cancelForm.value.reason
        })
        
        ElMessage.success('活动取消成功')
        showCancelDialog.value = false
        
        // 重新加载数据
        fetchCreatedActivities()
      } catch (error) {
        ElMessage.error('取消活动失败')
      } finally {
        cancelling.value = false
      }
    }
    
    // 同意报名
    const handleApproveRegistration = async (registrationId) => {
      try {
        await approveRegistration(registrationId)
        ElMessage.success('已同意报名')
        fetchParticipants()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    // 拒绝报名
    const handleRejectRegistration = async (registrationId) => {
      try {
        await rejectRegistration(registrationId)
        ElMessage.success('已拒绝报名')
        fetchParticipants()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    // 获取映射后的状态
    const getMappedStatus = (status) => {
      return mapStatusToFrontend(status)
    }
    
    // 获取报名状态标签类型
    const getStatusTagType = (status) => {
      const typeMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return typeMap[status] || 'info'
    }
    
    // 获取报名状态文本
    const getRegistrationStatusText = (status) => {
      const textMap = {
        'PENDING': '待确认',
        'APPROVED': '已确认',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return textMap[status] || '未知'
    }
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleString('zh-CN')
    }
    
    onMounted(() => {
      fetchParticipatedActivities()
    })
    


    return {
      // 响应式变量
      activeTab,
      loading,
      participantsLoading,
      
      // 参与的活动相关
      participatedActivities,
      participatedTotal,
      participatedPageNum,
      participatedPageSize,
      participatedFilters,
      
      // 创建的活动相关
      createdActivities,
      createdTotal,
      createdPageNum,
      createdPageSize,
      createdFilters,
      
      // 参与者相关
      showParticipantsDialog,
      participants,
      currentActivityId,
      currentActivityNeedApproval,
      
      // 取消活动相关
      showCancelDialog,
      cancelForm,
      cancelFormRef,
      activityToCancel,
      cancelling,
      
      // 方法
      fetchParticipatedActivities,
      fetchCreatedActivities,
      fetchParticipants,
      editActivity,
      viewParticipants,
      handleCancelActivity,
      submitCancel,
      handleApproveRegistration,
      handleRejectRegistration,
      
      // 工具函数
      getMappedStatus,
      getStatusTagType,
      getRegistrationStatusText,
      formatDate
    }
  }
}
</script>

<style scoped>
.my-activities-page {
  min-height: calc(100vh - 180px);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.activities-content {
  padding: 20px 0;
}

.filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-select {
  width: 150px;
}

.filter-input {
  width: 250px;
}

.create-btn {
  margin-left: auto;
}

.loading-container {
  padding: 40px 20px;
}

.empty-container {
  text-align: center;
  padding: 80px 20px;
}

.activities-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.activity-item {
  position: relative;
  transition: transform 0.3s, box-shadow 0.3s;
}

.activity-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.1);
}

.activity-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
  background: rgba(255, 255, 255, 0.9);
  padding: 5px;
  border-radius: 4px;
}

.activity-item:hover .activity-actions {
  opacity: 1;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.empty-participants {
  padding: 40px 20px;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-select,
  .filter-input {
    width: 100%;
  }
  
  .create-btn {
    margin-left: 0;
  }
  
  .activities-list {
    grid-template-columns: 1fr;
  }
  
  .activity-actions {
    position: static;
    opacity: 1;
    margin-top: 10px;
    justify-content: center;
  }
}
</style>